<template>
  <div id="NavMenu" class="nav-menu-wrapper">
    <el-menu
        :default-active="toIndex"
        class="el-menu-demo"
        text-color="#000000"
        active-text-color="#3989fa"
        mode="horizontal"
        @select="handleSelect"
    >
      <el-menu-item v-for="(item, index) in itemList" :index="item.path" :key="index">
        <span slot="title">{{ item.title }}</span>
      </el-menu-item>
      <div class="right-menu-items">
        <el-menu-item v-if="loggedInUserName" class="username-menu-item">
          <span class="username">当前用户: {{ loggedInUserName }}</span>
        </el-menu-item>
        <el-menu-item index="/Logout" class="logout-item" @click="handleLogout">
          <span>退出登录</span>
        </el-menu-item>
      </div>
    </el-menu>
    <el-main>
      <router-view></router-view>
    </el-main>
  </div>
</template>

<script>
export default {
  name: "NavMenu",
  data() {
    return {
      itemList: [
        { path: '/Wages', title: '工资' },
        { path: '/Personal', title: '个人信息' },
      ],
      loggedInUserName: ''
    };
  },
  computed: {
    toIndex() {
      return '/' + this.$route.path.split('/')[1];
    },
  },
  mounted() {
    this.fetchLoggedInUserName();
  },
  methods: {
    handleSelect(path) {
      if (path === '/Logout') {
        return false;
      }
      this.$router.push({ path });
    },
    async handleLogout() {
      try {
        const response = await this.$axios.get(`/user/loginOut`, {
          headers: {
            'satoken': localStorage.getItem('satoken'),
            'Content-Type': 'application/json',
          }
        });
        if (response.data.success) {
          this.$message({
            message: '注销登录成功',
            type: 'success'
          });
          this.$router.push('/')
        } else {
          this.$message.error(response.data.msg);
        }
      } catch (error) {
        console.error("请求错误:", error);
      }
    },
    fetchLoggedInUserName() {
      const nickName = localStorage.getItem('nickName');
      if (nickName) {
        this.loggedInUserName = nickName;
      }
    }
  },
};
</script>

<style scoped>
.nav-menu-wrapper {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  z-index: 999;
}
.right-menu-items {
  display: flex;
  justify-content: flex-end;
  align-items: center;
}
.logout-item {
  margin-left: 10px;
}
.username-menu-item {
  margin-left: 10px;
}
</style>
